import
{ TimeConstraintType_Repeat,CollectData_TYPE_Form,CollectData_TYPE_Table,
} from '../common/common';

import moment from 'moment';
//获取字段有效性验证规则
export function getSimpleValidationRuleForItem(ValidateDict,InforSetCodeKey,ItemCode,schema)
{
    let result={
        isRequired: false,
        max:null,
        maxLength:null,
        min:null,
        minLength:null,
        validateExpression: null
    }

    //如果是时间的规则配置
    if(ValidateDict&&InforSetCodeKey&&ItemCode)
    {
        //得到该信息集在该字段的组合Key
        let itemKey=InforSetCodeKey.split("_")[0]+"."+ItemCode;

        //如果存在当前Key，则收录该字段相关规则
        if(ValidateDict[itemKey])
        {
            let ItemResult=ValidateDict[itemKey];
            result.isRequired=ItemResult.isRequired;
            result.max=ItemResult.max;
            result.maxLength=ItemResult.maxLength;
            result.min=ItemResult.min;
            result.minLength=ItemResult.minLength;
            result.validateExpression=ItemResult.validateExpression;
        }
        else
        {
            result.isRequired=schema.isRequired;
            result.max=schema.max;
            result.maxLength=schema.maxLength;
            result.min=schema.min;
            result.minLength=schema.minLength;
            result.validateExpression=schema.validateExpression;
        }
    }
    //如果是信息集的字段规则配置
    else
    {
        result.isRequired=schema.isRequired;
        result.max=schema.max;
        result.maxLength=schema.maxLength;
        result.min=schema.min;
        result.minLength=schema.minLength;
        result.validateExpression=schema.validateExpression;
    }
    return result;
}
function addScriptTarget(name) {
    var script=document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", `./server_js/${name}.js`);
    var heads = document.getElementsByTagName("head");
    if(heads.length){
        heads[0].appendChild(script);
    } else{
        document.documentElement.appendChild(script);
    }
}



/*根据下拉框数据获取指定value对应的name*/
export function GetNameValueByValue(code,CodeValueArry) {
    let name=code;
    CodeValueArry.map(function (codeValue, j) {
        if(codeValue.value && codeValue.value==code)
        {
            name=codeValue.name;
            return;
        }
    });
    return name;
}


//重新遍历执行当前的function集合
export function excuteCurrentItemCodeEvent(functionSettings,rootComponent,currentFormKey,get,set ) {
    //functionSettings包含了{FunctionName,Name,eventParas}的数组
    //如果该事件拥有一系列处理函数则进行执行
    if(functionSettings.length>0&&rootComponent&&currentFormKey)
    {
        for (let functionSettingItem of functionSettings)
        {
            let CurrentFormFunctionSetting=functionSettingItem;
            console.log(CurrentFormFunctionSetting)
            addScriptTarget(CurrentFormFunctionSetting.functionName)
            var fn = eval(CurrentFormFunctionSetting.functionName)
            console.log('fn:');
            console.log(fn);

            let  options=CurrentFormFunctionSetting.eventParas;

            //组装get,set,以及当前form表单指针到options里面
            if(get)
            {
                options.getValue=get;
            }
            if(set)
            {
                options.setValue=set;
            }

            //传递当前的FormKey以及根节点
            options.rootComponent=rootComponent;

            console.log("currentFormKey")
            console.log(currentFormKey);
            console.log(rootComponent);
            options.currentFormKey=currentFormKey;

            fn(options);
        }
    }
}

export function CombineSubCodeWithTimeType(schemaSubTypes,schemaTimeConstraints,Language)
{
    //收集子类型中对应的时间约束集合
    let GetTimeTypesForSubCode=[];

    for(let SubType of schemaSubTypes)
    {
        console.log("schemaSubTypes[SubType]:",SubType);
        for(let TimeConstraint of schemaTimeConstraints)
        {
            if (SubType.code==TimeConstraint.subTypeCode)
            {
                GetTimeTypesForSubCode.push({"code":SubType.code,
                    "name": SubType.name[Language],
                    "timeType":TimeConstraint.timeType});
            }
        }
    }
    //收集最终形成的组合SubCode以对应的时间约束类型
    let ReallyTimeTypesWithSubCode=[];
    //收集时间约束为3的子类型集合
    let TimeTypesIsListWithSubCode=[];

    //循环遍历子类型中对应的时间约束集合，分离出以上数据
    for(let item of GetTimeTypesForSubCode)
    {
        if (item.timeType=="3")
        {
            TimeTypesIsListWithSubCode.push({"code":item.code,
                "name": item.name,
                "timeType":item.timeType});
        }
        else
        {
            ReallyTimeTypesWithSubCode.push({"code":item.code, "name": item.name,"timeType":item.timeType});
        }
    }

    //如果存在时间约束为3的子类型，那么需要合并他们，然后加入最终子类型集合序列
    if (eval(TimeTypesIsListWithSubCode).length!=0)
    {
        let Codes='';
        let Names='';
        for(let item of TimeTypesIsListWithSubCode)
        {
            Codes+=item.code+'_';
            Names+=item.name+'_';
        }
        Codes=Codes.substring(0,Codes.length-1);
        Names=Names.substring(0,Names.length-1);
        ReallyTimeTypesWithSubCode.push({"code":Codes,name:Names,"timeType":"3"});
    }

    return ReallyTimeTypesWithSubCode;
}

//遍历传递来的规则尝试发现对于数据字典里面Key:InfoSetCode.ItemCode的规则约束，逐一提取
//提取一个有关该字段的onChange,OnBlur等事件的相关触发函数的集合
export function getCurrentFunctionRelationSettings(rule,functionName,InfoSetCode,itemCode,InfoSetCreateDtos) {

    //保存该字段关于该事件如onBlur,onChange的配置集合数组
    let result=[];

    //取出事件字典
    let eventDic=rule.eventDict;

    //取出实际的InfoSetCode
    InfoSetCode=InfoSetCode.split("_")[0];

    //该字段的事件Key
    let eventKey=InfoSetCode+"."+itemCode;


    //然后找到信息集Code.itemCode一致的的字典Key,然后遍历里面的规则方法，寻找到对应事件的
    if(eventDic[eventKey])
    {
        let currentColumnsRule=eventDic[eventKey];

        for(let eventIndex of currentColumnsRule)
        {
            let eventItem=eventIndex;
            //如果事件的Name==functionName
            if(eventItem.name==functionName)
            {
                //取出EventParas
                var fields = JSON.parse(eventItem.option.eventParas.fieldDefines.replace(/'/g, '"'));

                var to = fields.ToCol;

                if(to)
                {
                    let toInfoSetSchemaList=[];

                    for(let i of to)
                    {
                        let  toInfoSetCode=i.icode;

                        //判断是否存在这个信息集COde
                        let isNotExist=true;
                        if(toInfoSetSchemaList.length>0)
                        {
                            for (let index of toInfoSetSchemaList)
                            {
                                if(index.InfoSetCode==toInfoSetCode)
                                {
                                    isNotExist=false;
                                }
                            }
                        }

                        if(isNotExist)
                        {
                            let schema=InfoSetCreateDtos[toInfoSetCode];

                            if(schema)
                            {
                                //取出当前信息集
                                //里接受信息集的Schema以便于下层分析出有哪些子类型的Form，以便于触发多个相邻表单的修正
                                let infoSetSchema=CombineSubCodeWithTimeType(schema.subTypes,schema.timeConstraints,"zh");

                                let fileterTimeTypeThree=[];

                                //去除时间约束为3的子类型
                                for (let item in infoSetSchema)
                                {
                                    if(item.timeType!="3")
                                    {
                                        fileterTimeTypeThree.push(item.code);
                                    }
                                }

                                toInfoSetSchemaList.push({ "InfoSetCode": toInfoSetCode, "InforSetForm": fileterTimeTypeThree});

                            }
                        }
                    }
                    eventItem.option.eventParas.toInfoSetSchemaList=toInfoSetSchemaList;
                }


                let event={ functionName: eventItem.functionName, name:eventItem.name, eventParas: eventItem.option.eventParas};

                result.push(event);
            }
        }
    }

    return result;
}
//遍历执行该信息集字段的相关关联函数
export function performanceCurrentFiledRealtionFunctionBYEvent(rule,functionName,InfoSetCode,itemCode,rootComponent,currentFormKey,get,set,InfoSetCreateDtos)
{
    // debugger
    console.log("进入触发事件2");
    console.log(rule.eventDict);
    console.log(functionName);
    console.log(InfoSetCode);
    console.log(itemCode);
    console.log(rootComponent);
    console.log(currentFormKey);
    console.log(InfoSetCreateDtos);

    if((rule.eventDict!=null)&&functionName&&InfoSetCode&&itemCode&&rootComponent&&currentFormKey&&InfoSetCreateDtos)
    {
        console.log("进入触发事件3");
        let functionList=getCurrentFunctionRelationSettings(rule,functionName,InfoSetCode,itemCode,InfoSetCreateDtos);
        console.log(functionList);
        excuteCurrentItemCodeEvent(functionList,rootComponent,currentFormKey,get,set);
    }
}


export function getValue(options) {
    // var ID=options.seq=='' ? '':options.seq
    // var elementLocal=options.icode + options.fcode + ID;
    // return options.form.getFieldValue(elementLocal);
    var elementLocal=options.currentFormKey+"_"+options.fcode;
    if(options.fcode=='begin')
    {
        elementLocal=options.fcode;
        return options.rootComponent.state[options.currentFormKey+'_'+'A0004'].props.form.getFieldValue(elementLocal);
    }

    console.log(options.currentFormKey);
    console.log(elementLocal);
    return options.rootComponent.state[options.currentFormKey].props.form.getFieldValue(elementLocal);
}

export  function setValue(options, val) {

    //循环渲染其他Form的字段值
    for(var index=0;index<options.currentFormKeys.length;index++)
    {
        var elementLocal=options.currentFormKeys[index]+"_"+options.fcode;
        options.rootComponent.state[options.currentFormKeys[index]].props.form.setFieldsValue( { [elementLocal]: val});
    }
}


export  function GetInfoSetData(rootComponent, schema,actionCode)
{
    if(schema)
    {
        
        //当前信息集的Code
        let infosetCode=schema.infoSetCode;

        let Result={ isSuccess: true, infoSetData: null }

        let infoSetData=[];
      
        //对每个单独的Form进行验证
        //如果不存在子类型
        if(eval(schema.subTypes).length==0)
        {
           
            //查询默认的时间约束类型
            let currentTimeType=schema.timeConstraints[0].timeType;

            //如果时间约束不是3那么通过getfiledValues去收集数据
            if(currentTimeType!=TimeConstraintType_Repeat)
            {
               
                rootComponent.state[infosetCode].props.form.validateFieldsAndScroll((errors, values) => {
                    if (errors) {
                        Result.isSuccess=false;
                    }
                    else
                    {
                        
                       
                        //获取表单数据
                        let FieldListData=rootComponent.state[infosetCode].props.form.getFieldsValue();

                        console.log('mark');
                        console.log(FieldListData);

                        let InfoSetValueDTO=GetInfoSetValueDTO(schema,FieldListData,infosetCode,CollectData_TYPE_Form,rootComponent);
                        let InfoSetValueMaintainJson={};
                        InfoSetValueMaintainJson.infoSetCode=infosetCode;
                        InfoSetValueMaintainJson.BeginDate=FieldListData["begin"].format("YYYY-MM-DD");
                        InfoSetValueMaintainJson.EndDate=FieldListData["end"].format("YYYY-MM-DD");
                        InfoSetValueMaintainJson.subTypeCode='';
                        InfoSetValueMaintainJson.vid=FieldListData["vid"];
                        InfoSetValueMaintainJson.fieldValueList=InfoSetValueDTO;
                        infoSetData.push(InfoSetValueMaintainJson);
                    }

                });
            }
            else
            {
                //获取表格数据
                let tableSource=rootComponent.state[infosetCode].state.value;
                //循环表格进行添加数据
                for(let dataItem of tableSource)
                {
                    let InfoSetValueDTO=GetInfoSetValueDTO(schema,dataItem,infosetCode,CollectData_TYPE_Table);
                    let InfoSetValueMaintainJson={};
                    InfoSetValueMaintainJson.infoSetCode=infosetCode;
                    InfoSetValueMaintainJson.BeginDate=dataItem["begin"];
                    InfoSetValueMaintainJson.EndDate=dataItem["end"];
                    InfoSetValueMaintainJson.vid=dataItem["vid"];
                    InfoSetValueMaintainJson.subTypeCode=dataItem["subTypeCode"];
                    InfoSetValueMaintainJson.fieldValueList=InfoSetValueDTO;
                    infoSetData.push(InfoSetValueMaintainJson);
                }
            }
        }
        else
        {
            if (schema.timeConstraints.length==1)
            {
                let StepKey=infosetCode+"_"+actionCode;
                let FieldListData=rootComponent.state[StepKey].props.form.getFieldsValue();
                let InfoSetValueDTO=GetInfoSetValueDTO(schema,FieldListData,StepKey,CollectData_TYPE_Form);
                let InfoSetValueMaintainJson={};
                InfoSetValueMaintainJson.infoSetCode=infosetCode;
                InfoSetValueMaintainJson.BeginDate=FieldListData["begin"].format("YYYY-MM-DD");
                InfoSetValueMaintainJson.EndDate=FieldListData["end"].format("YYYY-MM-DD");
                InfoSetValueMaintainJson.subTypeCode=actionCode;
                InfoSetValueMaintainJson.vid=FieldListData["vid"];
                InfoSetValueMaintainJson.fieldValueList=InfoSetValueDTO;
                infoSetData.push(InfoSetValueMaintainJson);
            }
            else
            {
                //如果存在子类型
                //整合结构里面的子类型，以便于准确区分后台过来的字典数据
                let ReallyTimeTypesWithSubCode=CombineSubCodeWithTimeType(schema.subTypes,schema.timeConstraints,"zh");

                for (let item of ReallyTimeTypesWithSubCode)
                {
                    /*时间约束不为3的*/
                    if (item.timeType!=TimeConstraintType_Repeat)
                    {

                        let StepKey=infosetCode+"_"+item.code;

                        rootComponent.state[StepKey].props.form.validateFieldsAndScroll((errors, values) => {
                            if (errors) {
                                Result.isSuccess=false;
                            }
                            else
                            {
                                let FieldListData=rootComponent.state[StepKey].props.form.getFieldsValue();
                                console.log("FieldListData",FieldListData)
                                let InfoSetValueDTO=GetInfoSetValueDTO(schema,FieldListData,StepKey,CollectData_TYPE_Form);
                                let InfoSetValueMaintainJson={};
                                InfoSetValueMaintainJson.infoSetCode=infosetCode;
                                InfoSetValueMaintainJson.BeginDate=FieldListData["begin"].format("YYYY-MM-DD");
                                InfoSetValueMaintainJson.EndDate=FieldListData["end"].format("YYYY-MM-DD");
                                InfoSetValueMaintainJson.subTypeCode=item.code;
                                InfoSetValueMaintainJson.vid=FieldListData["vid"];
                                InfoSetValueMaintainJson.fieldValueList=InfoSetValueDTO;
                                infoSetData.push(InfoSetValueMaintainJson);
                            }

                        });
                    }
                    else
                    {
                        let StepKey=infosetCode+"_"+item.code;
                        let tableSource=rootComponent.state[StepKey].state.value;
                        for(let dataItem of tableSource)
                        {
                            let InfoSetValueDTO=GetInfoSetValueDTO(schema,dataItem,StepKey,CollectData_TYPE_Table);
                            let InfoSetValueMaintainJson={};
                            InfoSetValueMaintainJson.infoSetCode=infosetCode;
                            InfoSetValueMaintainJson.BeginDate=dataItem["begin"];
                            InfoSetValueMaintainJson.EndDate=dataItem["end"];
                            InfoSetValueMaintainJson.vid=dataItem["vid"];
                            InfoSetValueMaintainJson.subTypeCode=dataItem["subTypeCode"];
                            InfoSetValueMaintainJson.fieldValueList=InfoSetValueDTO;
                            infoSetData.push(InfoSetValueMaintainJson);
                        }
                    }
                }
            }

        }

        Result.infoSetData=infoSetData;
        return Result;
    }
}


/*获取单个信息集属性和值*/
export function GetInfoSetValueDTO(schema,FieldListData,StepKey,Type,rootComponent)
{
    let InfoSetValueDTO=[];
    for (let item of schema.fieldList)
    {
        let json={};
        json.code=item.code;
        if(Type=="Form")
        {
            let currentFieldValue=FieldListData[StepKey+'_'+item.code];
            var m = moment.invalid(currentFieldValue);
            if (m._pf._isValid)
            {
                json.currentFieldValue= currentFieldValue.format("YYYY-MM-DD");
            }
            else
            {
                if(schema.subFieldList!=null&&schema.subFieldList.length>0)
                {
                    //获取子信息显示的表格数据
                    schema.subFieldList.map(function (SubSchema, j) {
                        if(SubSchema.fieldName==json.code)
                        {
                            let key=SubSchema.infoSetCode+"_"+SubSchema.fieldName;
                            let tableSource=rootComponent.refs[key].state.value;
                            let tableSourceForSave=[];
                            tableSource.map(function (subData, j) {
                                let FieldKeys = Reflect.ownKeys(subData);
                                let rowData={};
                                FieldKeys.map(function (key, j) {
                                    SubSchema.fieldList.map(function (f, j) {
                                        if(f.code==key)
                                        {
                                            rowData[f.code]=subData[f.code];
                                        }
                                    });
                                });
                                tableSourceForSave.push(rowData);
                            });
                            currentFieldValue= JSON.stringify(tableSourceForSave);
                        }
                    });
                }
                json.currentFieldValue= currentFieldValue;
            }
        }
        else
        {

            json.currentFieldValue= FieldListData[item.code];
        }

        InfoSetValueDTO.push(json);
    }
    return InfoSetValueDTO;
}